import { createRouter, createWebHistory } from 'vue-router'
import { useServerUserStore } from '@/stores'
import { useUserStore } from '@/stores/modules/user-student'

import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path:'/imitate-login',
      name:'模拟登录', 
      component: () => import('@/views/zym-sever/ImitateLogin.vue'), 
    },
    // { path:'/login', component: () => import('@/views/login/MyLogin.vue') },
    { path:'/',redirect:'/server'},
    {
      path: '/server',
      name: '服务端布局',
      component: () => import('@/views/server/ServerLayout.vue'),
      children: [
        {
          path: 'review-task-scheduling',
          name: '评阅任务调度',
          component: () => import('@/views/zym-sever/ReviewTaskScheduling.vue'),
          meta: {
            requiresAuth: true,
            requiredRoleId: 2, // 学科组长权限
          }
        },
        {
          path: 'task-manage',
          name: '评阅任务管理',
          component: () => import('@/views/zym-sever/TaskManage.vue'),
        },
        {
          path: 'test',
          name: '试卷批阅',
          component: () => import('@/views/zym-sever/Test.vue'),
        },
        {
          path: 'recheck-request',
          name: '查卷申请',
          component: () => import('@/views/zym-sever/recheckRequest/RecheckRequest.vue'),
          meta: {
            requiresAuth: true,
            requiredRoleId: 3, // 教师
          }
        },
        {
          path: 'recheck-request-manage',
          name: '查卷申请管理',
          component: () => import('@/views/zym-sever/recheckRequestManage/RecheckRequestManage.vue'),
          meta: {
            requiresAuth: true,
            requiredRoleId: 2, // 学科组长
          }
        },
        {
          path: 'recheck-task',
          name: '复查任务',
          component: () => import('@/views/zym-sever/recheckTask/RecheckTask.vue'),
        },
        {
          path: 'backup-data',
          name: '备份数据',
          component: () => import('@/views/zym-sever/backupData/BackupComponent.vue'),
        },
        {
          path: 'score-analysis-export',
          name: '成绩分析与导出',
          component: () => import('@/views/zym-sever/scoreAnalysisExport/ScoreAnalysisExport.vue'),
        } 
      ]
    },
    {
      path: '/whole-paper-review',
      name: '整张试卷批阅',
      component: () => import('@/views/zym-sever/WholePaperReview.vue'),
    },
    {
      path: '/single-question-review',
      name: '单道大题批阅',
      component: () => import('@/views/zym-sever/SingleQuestionReview.vue'),
    },
    {
      path: '/recheck-component',
      name: '复查界面',
      component: () => import('@/views/zym-sever/recheckTask/RecheckComponent.vue'),
    },
    {
      path: '/score-analysis',
      name: '成绩分析',
      component: () => import('@/views/zym-sever/scoreAnalysisExport/scoreAnalysis.vue'),
    },



    //  沈进部分
    {
      path: '/sj-login',
      name: 'sjLogin',
      component: () => import('../views/sj/Login.vue')
    },
    {
      path: '/forget-password',
      name: 'ForgetPassword',
      component: () => import('../views/sj/ForgetPassword.vue')
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('../views/sj/Home.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'Dashboard',
          component: () => import('../views/sj/Dashboard.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('../views/sj/Dashboard.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'subject',
          name: 'Subject',
          component: () => import('../views/sj/Subject.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'subject-detail/:id',
          name: 'SubjectDetail',
          component: () => import('../views/sj/SubjectDetail.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'question',
          name: 'Question',
          component: () => import('../views/sj/Question.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'Paper',
          name: 'Paper',
          component: () => import('../views/sj/Paper.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'user',
          name: 'User',
          component: () => import('../views/sj/User.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'role',
          name: 'Role',
          component: () => import('../views/sj/Role.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'teacher-classes-subject',
          name: 'TeacherClassesSubject',
          component: () => import('../views/sj/TeacherClassesSubject.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'classes',
          name: 'Classes',
          component: () => import('../views/sj/Classes.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'profile',
          name: 'Profile',
          component: () => import('../views/sj/Profile.vue'),
          meta: { requiresAuth: true }
        }
      ]
    },


    // 谭昊部分
    {
      path: '/login',
      name: 'th-Login',
      component: () => import('@/views/client/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/exam',
      component: () => import('@/views/client/Layout.vue'),
      name:'th-exam',
      meta: { requiresAuth: true },
      children: [
        {
          path: 'list',
          name: 'th-ExamList',
          component: () => import('@/views/client/exam/List.vue')
        },
        {
          path: ':id',
          name: 'th-ExamDetail',
          component: () => import('@/views/client/exam/Detail.vue')
        },
        {
          path: ':id/take',
          name: 'th-ExamTake',
          component: () => import('@/views/client/exam/Take.vue')
        }
      ]
    },{
      path: '/score',
      component: () => import('@/views/client/Layout.vue'),
      name:'th-score',
      meta: { requiresAuth: true },
      children: [
        {
          path: 'list',
          name: 'th-ScoreList',
          component: () => import('@/views/client/score/List.vue')
        },
        {
          path: ':id',
          name: 'th-ScoreDetail',
          component: () => import('@/views/client/score/Detail.vue')
        }
      ]
    },
    {
      path: '/change-machine',
      name: 'th-ChangeMachine',
      component: () => import('@/views/client/ChangeMachine.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'th-Profile',
      component: () => import('@/views/client/Profile.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'th-NotFound',
      component: () => import('@/views/client/NotFound.vue')
    },

  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {

  console.log('to: ', to);
  

  const userStore = useServerUserStore()
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 如果未登录，需要先登录
    if (!userStore.token) {
      ElMessage.error('请先登录')
      // 重定向到登录页面，此处需要替换为真实的登录路由
      // next('/login')
      next(false)
      return
    }
    
    // 检查是否有特定角色权限要求
    if (to.meta.requiredRoleId !== undefined) {
      const hasRequiredRole = userStore.userInfo?.roleId === to.meta.requiredRoleId
      
      if (!hasRequiredRole) {
        ElMessage.error('您没有权限访问该页面')
        next(false)
        return
      }
    }
  }
  
  // 通过权限验证，放行
  next()
  console.log('放行了！')

  if(to.path.includes('sj')){
    const token = localStorage.getItem('token')
  const userInfoStr = localStorage.getItem('userInfo')
  let userInfo = null

  try {
    if (userInfoStr && userInfoStr !== 'undefined') {
      userInfo = JSON.parse(userInfoStr)
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
    // 解析失败，清除可能无效的 token 和 userInfo
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    // 重定向到登录页
    if (to.path !== '/login') {
      next('/login')
      return
    }
  }

  // 1. 处理已登录用户访问登录页或根路径
  if (token && userInfo) {
    if (to.path === '/login' || to.path === '/') {
      next('/home/dashboard') // 已登录，访问登录页或根路径，重定向到仪表盘
      return
    }
  } else {
    // 2. 处理未登录用户访问需要认证的页面
    if (to.meta.requiresAuth) {
      next('/login') // 未登录，访问需认证页面，重定向到登录页
      return
    }
  }

  // 3. 检查需要认证的页面的权限 (此时确保用户已登录且 userInfo 已解析)
  if (to.meta.requiresAuth && userInfo) {
    // 检查用户角色是否允许登录系统
    const allowedRoles = ['管理员', '学科组长', '教师']
    if (!allowedRoles.includes(userInfo.roleName)) {
      // 如果角色不允许登录，则清除登录信息并重定向到登录页，并附带错误提示
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      next({ path: '/login', query: { error: 'role_not_allowed' } })
      return
    }

    // 检查学科详情页权限
    if (to.name === 'SubjectDetail' && userInfo.roleName !== '管理员') {
      const subjectIdParam = parseInt(to.params.id, 10) // 明确指定基数
      // 确保 userInfo.subjects 存在且是数组类型
      const userSubjectIds = userInfo.subjects ? userInfo.subjects.map(subject => parseInt(subject.id, 10)) : [];
      
      if (!userSubjectIds.includes(subjectIdParam)) {
        console.warn(`权限不足: 用户 (${userInfo.username}, 角色: ${userInfo.roleName}, 学科ID: ${userSubjectIds}) 尝试访问学科详情页 (ID: ${subjectIdParam})`)
        next('/home/subject') // 用户没有该学科的权限或学科ID无效，重定向到学科列表页
        return
      }
    }
  }

  // 4. 其他情况，允许导航
  next()
  }


  if(to.name.includes('th')){

  }

})

export default router
